var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// 引入Token验证的依赖包
var jwt = require('express-jwt');
/* 
  secretKey:秘钥，Token
  unless ：排除不需要做 Token 验证的路径（即：页面）
  algorithms：加密算法
*/
var {secretKey,unless,algorithms} = require('./utils/token'); // 引入自定义配置信息

require('./db');      // 引入数据库

// 引入路由
var indexRouter = require('./routes/index');
var userRouter = require('./routes/user');  // 用户管理
var adminRouter = require('./routes/admin');  // 管理员
var shopDoorsRouter = require('./routes/shopDoors');  // 门店
var commoditysRouter = require('./routes/commoditys');  // 商品
var serviceRouter = require('./routes/service');  // 服务
var orderServiceRouter = require('./routes/orderService');  // 订单服务
var applyForRouter = require('./routes/applyFor');  // 申请
var orderGoodRouter = require('./routes/orderGood');  //商品订单
var addressRouter = require('./routes/address');    // 地址



var app = express();

// // 配置jwt的密钥、加密算法，以及不需要认证的路径，下面代码一定要放在var app = express();的后面
app.use(jwt({secret: secretKey,algorithms}).unless(unless));


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/user', userRouter); // 用户管理
app.use('/admin', adminRouter); // 用户管理
app.use("/shopDoors",shopDoorsRouter)//门店
app.use("/commoditys",commoditysRouter)//商品
app.use("/service",serviceRouter)//服务
app.use("/orderService",orderServiceRouter)//订单
app.use("/applyFor",applyForRouter)//商品
app.use("/orderGood",orderGoodRouter)//商品订单
app.use("/address",addressRouter)    // 地址


// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // 如果 Token 认证失败返回401状态和invalid token字符串（if 内容是自己为了进行 Token 验证的时候配置的）
  if (err.name === "UnauthorizedError") {
    res.status(401).send("invalid token");
  } else {
    // render the error page
    res.status(err.status || 500);
    console.log("error:", err.message);
    res.render('error');
  }
});

module.exports = app;